package com.sfx.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.sfx.domain.ResponseResult;
import com.sfx.enums.AppHttpCodeEnum;
import com.sfx.exception.SystemException;
import com.sfx.service.UploadService;
import com.sfx.utils.PathUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;

import static com.sfx.constants.SystemConstants.EXTERNAL_LINK_PREFIX;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-07-13
 * Time: 13:41
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Value("${oss.accessKey}")
    private String accessKey;

    @Value("${oss.secretKey}")
    private String secretKey;

    @Value("${oss.bucket}")
    private String bucket;

    @Override
    public ResponseResult uploadImg(MultipartFile img) {
        //1.获取原始文件名
        String originalFilename = img.getOriginalFilename();
        //2.判断文件类型
        if(!originalFilename.substring(originalFilename.indexOf(".") +1).equals("png")) {
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        //3.生成文件路径filePath
        String filePath = PathUtils.generateFilePath(originalFilename);
        //4.返回生成好的外链
        return uploadOss(img,filePath);
    }

    private ResponseResult uploadOss(MultipartFile img, String filePath) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;

        try {
            FileInputStream inputStream = (FileInputStream) img.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return ResponseResult.okResult(EXTERNAL_LINK_PREFIX + key);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return ResponseResult.okResult("nono");
    }
}
